<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\shop_admin\controller;

use app\BaseController;
use think\App;
use think\Exception;
use think\facade\Env;
use think\helper\Str;

/**
 * 基类
 * @package app\shop_admin\controller
 */
class BaseAction extends BaseController
{

    protected $data;

    protected $user;

    protected $profiles;

    /**
     * BaseAction constructor.
     * @param App $app
     * @throws Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->profiles = Env::get("profiles");

        global $user;
        switch ($this->profiles) {
            case "pro":
                $this->user = $user;
                break;
            case "dev":
                $user = (object)['mall_id' => 87080,'merchant_id' => 59];
                $this->user = $user = \app\shop_admin\model\Admin::find(6);
                global $uri;
                $uri = Str::lower(request()->pathinfo());
                break;
        }

        if ($user && $user->affiliation === "shop"){
            $flag = $this->checkAuth();
            if (!$flag) {
                throw new Exception('没有权限', HTTP_FORBIDDEN);
            }
        }

        if ($this->request->action() === 'findAll') {
            $this->data = array_filter($this->request->post(), 'filterArr');
        }

    }


    /**
     * 路由权限校验
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function checkAuth()
    {
        global $user, $uri;

        if ($user->is_root === 1){
            return true;
        }

        $dischargedArr = [
            'operation/login',
            'operation/logout',
            'upload/images',
            'statistic/exportUser',
            'statistic/exportCommodity',
            'lessee/entry',
        ];
        if (in_array($uri, $dischargedArr, true)) {
            return true;
        }


        if (!property_exists($user,'flag')) {
            return true;
        }

        $rootUri = request()->root() . "/" . request()->rule()->getRule();

        $rootDischargedArr = [
            '/shop/admin/selfUp/<id>',
            '/shop/addons'
        ];
        if (in_array($rootUri, $rootDischargedArr, true)) {
            return true;
        }

        $pageAction = request()->header('PageAction');
        if (empty($pageAction)) {
            return false;
        }
        $explode = explode(",", $pageAction);
        if (count($explode) < 2) {
            return false;
        }
        $level = (int)$explode[0];
        $action = (string)$explode[1];

        if ($user->flag){
            $ruleId = \app\madmin\model\Rule::where(['resource' => $action, 'level' => $level])->value('id');
            if (empty($ruleId)) {
                return false;
            }

            $roleRule = \app\madmin\model\RoleRule::where(['role_id' => $user->role_id, 'rule_id' => $ruleId])->find();
            if (!$roleRule) {
                return false;
            }
            $ruleExtend = \app\madmin\model\RuleExtend::where(['rule_id' => $ruleId, "rule_route" => $rootUri, "method" => request()->method()])->find();
            if (!$ruleExtend) {
                return false;
            }
        }else{
            $ruleId = \app\shop_admin\model\Rule::where(['resource' => $action, 'level' => $level])->value('id');
            if (empty($ruleId)) {
                return false;
            }

            $roleRule = \app\shop_admin\model\RoleRule::where(['role_id' => $user->role_id, 'rule_id' => $ruleId])->find();
            if (!$roleRule) {
                return false;
            }
            $ruleExtend = \app\shop_admin\model\RuleExtend::where(['rule_id' => $ruleId, "rule_route" => $rootUri, "method" => request()->method()])->find();
            if (!$ruleExtend) {
                return false;
            }
        }

        return true;
    }

    /**
     * 路由权限校验
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    /*protected function checkAuthOld()
    {
        global $user, $uri;

        $dischargedArr = [
            'operation/login',
            'operation/logout',
            'upload/images'
        ];
        if (in_array($uri, $dischargedArr, true)) {
            return true;
        }

        if (isset($user['flag']) && $user['flag']) {
            if (Cache::store('redis')->has(checkRedisKey('MALL_SHOP_RULE:' . $user->id))) {
                $ruleList = json_decode(Cache::store('redis')
                    ->get(checkRedisKey('MALL_SHOP_RULE:' . $user->id)), true);
            } else {
                $shopRuleIds = MallShopRule::where('role_id', $this->user->role->id)->value('rule_list');
                if ($shopRuleIds)
                    $shopRuleIds = json_decode($shopRuleIds, true);
                $ruleList = RuleExtend::where(['rule_id' => $shopRuleIds])
                    ->field('rule_route,method')
                    ->select();
                $ruleList = $ruleList ? $ruleList->toArray() : [];
                Cache::store('redis')->set(checkRedisKey('MALL_SHOP_RULE:' . $user->id), json_encode($ruleList));
            }
        } else {
//            if (Cache::store('redis')->has(checkRedisKey('SHOP_RULE:' . $user->id))) {
//                $ruleList = json_decode(Cache::store('redis')
//                    ->get(checkRedisKey('SHOP_RULE:' . $user->id)), true);
//            } else {

                $rule = $user->role->rule()->where('rule.status', 1)->select();
                if (empty($rule))
                    throw new Exception("无权访问", HTTP_NOTACCEPT);
                $ruleIds = array_column($rule->toArray(), 'id');
                $ruleList = RuleExtend::where(['rule_id' => $ruleIds])
                    ->field('rule_route,method')
                    ->select();
                $ruleList = $ruleList ? $ruleList->toArray() : [];
                Cache::store('redis')->set(checkRedisKey('SHOP_RULE:' . $user->id), json_encode($ruleList));
//            }
        }

        $uriArr = [];
        $uriArr['rule_route'] = request()->rule()->getRule();
        $uriArr['method'] = request()->method();

        if (!in_array($uriArr, $ruleList))
            return false;

        return true;
    }*/


}
